package com.rybbaby.tss.platform.sysPreserve.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.rybbaby.tss.core.annotation.RequestLog;
import com.rybbaby.tss.core.bean.TableBean;
import com.rybbaby.tss.core.bean.TableColumnBean;
import com.rybbaby.tss.core.utils.*;
import com.rybbaby.tss.core.web.controller.BaseController;
import com.rybbaby.tss.platform.sysPreserve.pojo.ExecSqlResult;
import com.rybbaby.tss.platform.sysPreserve.service.IDatabasePreserveService;
import com.rybbaby.tss.platform.sysHandlePermissions.entity.SysHandlePermissions;
import com.rybbaby.tss.platform.sysHandlePermissionsAttrs.entity.SysHandlePermissionsAttrs;
import com.rybbaby.tss.platform.sysHandlePermissionsClasses.entity.SysHandlePermissionsClasses;
import com.rybbaby.tss.platform.sysHandlePermissionsEvents.entity.SysHandlePermissionsEvents;
import com.rybbaby.tss.platform.sysHandlePermissionsStyles.entity.SysHandlePermissionsStyles;
import com.rybbaby.tss.platform.sysMenuPermissions.entity.SysMenuPermissions;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.*;


/**
 * @author 谢进伟
 * @description 数据库维护
 * @createDate 2017/2/28 13:57
 */
@Controller
@RequestMapping(value = "preserve/database")
public class DatabasePreserveController extends BaseController {

    @Autowired
    private IDatabasePreserveService databasePreserveService;

    @RequestLog(content = "数据库维护")
    @RequestMapping(value = "databaseAceEdit")
    public ModelAndView databaseAceEdit() {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("databaseAceEditView"));
        String dbType = PropertiesReadUtil.getStringProperty("jdbc.dbType");
        dbType = "mysql".equals(dbType) ? dbType : ("sqlserver".equals(dbType) ? dbType : "sql");
        try {
            // sql编辑器自动补全数据
            List<Map<String, Object>> extendCompleteData = new ArrayList<Map<String, Object>>();
            List<TableBean> allTable = this.databasePreserveService.getAllTables();
            if (allTable != null && !allTable.isEmpty()) {
                allTable.parallelStream().sorted((o1, o2) -> {
                    return o1.getName().compareTo(o2.getName());
                }).forEachOrdered((table) -> {
                    /*
                     * meta：显示在提示框的右边
                     * caption：显示在提示框的左边
                     * value：是实际插入的数据
                     * score：表示优先级，高的排在前面
                     */
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("meta", table.getRemarks());
                    map.put("caption", table.getName());
                    map.put("value", table.getName());
                    map.put("score", 1);
                    extendCompleteData.add(map);
                });
            }
            mav.addObject("extendCompleteData", URLEncoder.encode(JSONUtil.toJsonStr(extendCompleteData), StandardCharsets.UTF_8.toString()));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        mav.addObject("dbType", dbType);
        return mav;
    }

    @RequestLog(content = "数据库表和视图树形")
    @RequestMapping(value = "databaseTablesTree")
    public ModelAndView databaseTablesTree() {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("databaseTablesTreeView"));
        return mav;
    }

    @ResponseBody
    @RequestLog(content = "获取数据库所有数据表json串")
    @RequestMapping(value = "getAllTable", method = RequestMethod.GET)
    public String getAllTable() {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            String catalog = getParameter("catalog");
            String tableName = getParameter("tableName");
            StringBuffer data = new StringBuffer();
            data.append("[");
            if (StringUtils.isBlank(tableName) && StringUtils.isBlank(catalog)) {// 加载表
                List<TableBean> allTable = this.databasePreserveService.getAllTables();
                if (allTable != null && !allTable.isEmpty()) {
                    allTable.parallelStream().sorted((o1, o2) -> {
                        String tableType1 = o1.getTableType();
                        String tableType2 = o2.getTableType();
                        if (!tableType1.equals(tableType2)) {
                            return tableType1.compareTo(tableType2);
                        }
                        return o1.getName().compareTo(o2.getName());
                    }).forEachOrdered((table) -> {
                        try {
                            String type = "";
                            String tableType = table.getTableType();
                            if (tableType != null) {
                                if ("VIEW".equals(tableType)) {// 视图
                                    type = " <i class=\'fa fa-braille red\'></i>&nbsp;";
                                }
                            }
                            String remarks = table.getRemarks();
                            data.append("{ name: \"" + type + "<span title=\'" + remarks + "\'>" + table.getName() + (StringUtils.isNotBlank(remarks) ? ("(" + remarks + ")") : "") + "</span>" + "\", type: \"" + "folder" + "\", params:" + JSONUtil.toJsonStr(table));
                            data.append(",data: [");
                            data.append("]},");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                }
            } else {// 加载字段
                info("加载" + catalog + "." + tableName + "字段");
                List<TableColumnBean> tableColumns = this.databasePreserveService.getTableColumns(catalog, tableName);
                tableColumns.parallelStream().sorted((o1, o2) -> {
                    Boolean o1IsPrimaryKey = BooleanUtils.toBoolean(o1.getIsPrimaryKey());
                    Boolean o2IsPrimaryKey = BooleanUtils.toBoolean(o2.getIsPrimaryKey());
                    Boolean o1IsForeignKey = BooleanUtils.toBoolean(o1.getIsForeignKey());
                    Boolean o2IsForeignKey = BooleanUtils.toBoolean(o2.getIsForeignKey());
                    if (o1IsPrimaryKey) {
                        return -1;
                    } else if (o2IsPrimaryKey) {
                        return 1;
                    } else if (o1IsForeignKey) {
                        return -1;
                    } else if (o2IsForeignKey) {
                        return 1;
                    } else {
                        return o1.getColumnName().compareTo(o2.getColumnName());
                    }
                }).forEachOrdered((column) -> {
                    try {
                        String icon = "<i class=\'fa fa-plug blue\'></i>";
                        String foreign = "";
                        if (BooleanUtils.toBoolean(column.getIsPrimaryKey())) {
                            icon = "<i class=\'fa fa-key yellow\'></i>";
                        } else if (BooleanUtils.toBoolean(column.getIsForeignKey())) {
                            icon = "<i class=\'fa fa-random red\'></i>";
                            String referenceTable = column.getReferenceTable();
                            String referenceColumn = column.getReferenceColumn();
                            foreign = "<i class=\'fa fa-long-arrow-right red\'></i>" + referenceTable + "(" + referenceColumn + ")";
                        }
                        String remarks = column.getRemarks();
                        data.append("{ name: \"" + icon + column.getColumnName() + (StringUtils.isNotBlank(remarks) ? ("(" + column.getRemarks() + ")") : "") + foreign + "\", type: \"" + "item" + "\", params:" + JSONUtil.toJsonStr(column));
                        data.append(",data: [");
                        data.append("]},");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
            if (data.length() > 1) {
                data.deleteCharAt(data.length() - 1);
            }
            data.append("]");
            ajr.setData(data);
        } catch (Exception e) {
            ajr.setResMsg(e.getMessage());
            ajr.setResCode(500);
            e.printStackTrace();
        }
        return ajr.jsonResponse(true);
    }

    @ResponseBody
    @RequestLog(content = "执行sql")
    @RequestMapping(value = "execSql")
    public ModelAndView execSql() {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("execSqlResultView"));
        try {
            String sql = getParameter("sql");
            List<ExecSqlResult> execResults = this.databasePreserveService.executeSql(sql);
            mav.addObject("execResults", execResults);
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    @ResponseBody
    @RequestLog(content = "保存sql")
    @RequestMapping(value = "saveSql", method = RequestMethod.POST)
    public void saveSql(HttpServletResponse response) {
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            String sql = getParameter("sql");
            String downFileName = SequenceUtil.getLowerCaseUUID();
            response.setHeader("Content-Disposition", "attachment;filename=" + downFileName + ".sql");
            IOUtils.write(URLDecoder.decode(sql, StandardCharsets.UTF_8.toString()), outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ResponseBody
    @RequestLog(content = "导出菜单、操作权限权限")
    @RequestMapping(value = "genSettingJSON", method = RequestMethod.GET)
    public void genSettingJSON(HttpServletResponse response) {
        //菜单
        String sqlForMenu = "SELECT * FROM sys_menu_permissions";
        //菜单操作权限
        String sqlForHandle = "SELECT * FROM sys_handle_permissions WHERE defaultHandlePermissionId IS NULL AND adminUserPermissionAllotId IS NULL AND rolePermissionAllotId IS NULL AND menuId IS NOT NULL";
        //操作权限class属性
        String sqlForHandleClasses = "SELECT * FROM sys_handle_permissions_classes WHERE handlePermissionId IS NOT NULL";
        //操作权限style属性
        String sqlForHandleStyles = "SELECT * FROM sys_handle_permissions_styles WHERE handlePermissionId IS NOT NULL";
        //操作权限event属性
        String sqlForHandleEvents = "SELECT * FROM sys_handle_permissions_events WHERE handlePermissionId IS NOT NULL";
        //操作权限attr属性
        String sqlHandleAttrs = "SELECT * FROM sys_handle_permissions_attrs WHERE handlePermissionId IS NOT NULL";
        List<Map<String, Object>> menuList = new ArrayList<>();
        List<Map<String, Object>> handleList = new ArrayList<>();
        List<Map<String, Object>> handleClassesList = new ArrayList<>();
        List<Map<String, Object>> handleStyleList = new ArrayList<>();
        List<Map<String, Object>> handleEventsList = new ArrayList<>();
        List<Map<String, Object>> handleAttrList = new ArrayList<>();
        try {
            menuList = this.databasePreserveService.findForJdbc(sqlForMenu, null);
            handleList = this.databasePreserveService.findForJdbc(sqlForHandle, null);
            handleClassesList = this.databasePreserveService.findForJdbc(sqlForHandleClasses, null);
            handleStyleList = this.databasePreserveService.findForJdbc(sqlForHandleStyles, null);
            handleEventsList = this.databasePreserveService.findForJdbc(sqlForHandleEvents, null);
            handleAttrList = this.databasePreserveService.findForJdbc(sqlHandleAttrs, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, Object> data = new TreeMap<>();
        data.put("menus", menuList);
        data.put("handles", handleList);
        data.put("handleClasses", handleClassesList);
        data.put("handleStyles", handleStyleList);
        data.put("handleEvents", handleEventsList);
        data.put("handleAttrs", handleAttrList);
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            String downFileName = "setting-" + DateUtil.format("yyyy-MM-dd") + SequenceUtil.getLowerCaseUUID();
            response.setHeader("Content-Disposition", "attachment;filename=" + downFileName + ".json");
            IOUtils.write(JSONUtil.toJsonStr(data), outputStream, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ResponseBody
    @RequestLog(content = "导入菜单、操作权限")
    @RequestMapping(value = "importConfig", method = RequestMethod.POST)
    public String importConfig(@RequestParam(required = true) String jsonConfig) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        ajr.setResMsg("导入成功!");
        Object loginUserIdObj = getLoginUserId();
        if (loginUserIdObj != null) {
            if (StringUtils.isNotBlank(jsonConfig)) {
                String loginUserId = loginUserIdObj.toString();
                JSONObject jsonObject = JSONObject.fromObject(jsonConfig);
                JSONArray menus = jsonObject.getJSONArray("menus");
                boolean isParseError = false;
                //已存在菜单
                String sqlForMenu = "SELECT id FROM sys_menu_permissions";
                List<Map<String, Object>> menuList = this.databasePreserveService.findForJdbc(sqlForMenu, null);
                List<String> menuIdList = new ArrayList<>();
                for (Map<String, Object> map : menuList) {
                    menuIdList.add(map.get("id").toString());
                }
                //解析菜单
                List<SysMenuPermissions> menuPermissionsList = new ArrayList<>();
                for (int i = 0, size = menus.size(); i < size; i++) {
                    JSONObject obj = menus.getJSONObject(i);
                    String id = JSONUtil.getStringVal(obj, "id");
                    if (StringUtils.isBlank(id)) {
                        isParseError = true;
                        break;
                    }
                    if (menuIdList.contains(id)) {
                        continue;
                    }
                    String pId = JSONUtil.getStringVal(obj, "pId");
                    String name = JSONUtil.getStringVal(obj, "name");
                    String icon = JSONUtil.getStringVal(obj, "icon");
                    String url = JSONUtil.getStringVal(obj, "url");
                    int weight = JSONUtil.getIntVal(obj, "weight");
                    Boolean isForbidden = JSONUtil.getBooleanVal(obj, "isForbidden");
                    String handlePermissionIdentifier = JSONUtil.getStringVal(obj, "handlePermissionIdentifier");
                    SysMenuPermissions smp = new SysMenuPermissions();
                    smp.setId(id);
                    smp.setpId(pId);
                    smp.setName(name);
                    smp.setIcon(icon);
                    smp.setUrl(url);
                    smp.setWeight(weight);
                    smp.setIsForbidden(isForbidden);
                    smp.setCreateUserId(loginUserId);
                    smp.setCreateTime(new Timestamp(System.currentTimeMillis()));
                    smp.setVersion(0);
                    smp.setHandlePermissionIdentifier(handlePermissionIdentifier);
                    menuPermissionsList.add(smp);
                }
                List<SysHandlePermissions> handlePermissionsList = new ArrayList<>();
                if (!isParseError) {
                    //已存在菜单操作权限
                    String sqlForHandle = "SELECT id FROM sys_handle_permissions WHERE defaultHandlePermissionId IS NULL AND adminUserPermissionAllotId IS NULL AND rolePermissionAllotId IS NULL AND menuId IS NOT NULL";
                    List<Map<String, Object>> handleList = this.databasePreserveService.findForJdbc(sqlForHandle, null);
                    List<String> handleIdList = new ArrayList<>();
                    for (Map<String, Object> map : handleList) {
                        handleIdList.add(map.get("id").toString());
                    }
                    //解析操作权限
                    JSONArray handles = jsonObject.getJSONArray("handles");
                    for (int i = 0, size = handles.size(); i < size; i++) {
                        JSONObject obj = handles.getJSONObject(i);
                        String id = JSONUtil.getStringVal(obj, "id");
                        if (StringUtils.isBlank(id)) {
                            isParseError = true;
                            break;
                        }
                        String defaultHandlePermissionId = JSONUtil.getStringVal(obj, "defaultHandlePermissionId");
                        String adminUserPermissionAllotId = JSONUtil.getStringVal(obj, "adminUserPermissionAllotId");
                        String rolePermissionAllotId = JSONUtil.getStringVal(obj, "rolePermissionAllotId");
                        String menuId = JSONUtil.getStringVal(obj, "menuId");
                        if (handleIdList.contains(id) || !(StringUtils.isBlank(defaultHandlePermissionId) &&
                                StringUtils.isBlank(adminUserPermissionAllotId) &&
                                StringUtils.isBlank(rolePermissionAllotId) &&
                                StringUtils.isNotBlank(menuId))) {
                            continue;
                        }
                        String name = JSONUtil.getStringVal(obj, "name");
                        String pageName = JSONUtil.getStringVal(obj, "pageName");
                        String code = JSONUtil.getStringVal(obj, "code");
                        String tagName = JSONUtil.getStringVal(obj, "tagName");
                        String innerHtml = JSONUtil.getStringVal(obj, "innerHtml");
                        String idAttr = JSONUtil.getStringVal(obj, "idAttr");
                        int weight = JSONUtil.getIntVal(obj, "weight");
                        Boolean isForbidden = JSONUtil.getBooleanVal(obj, "isForbidden");
                        SysHandlePermissions shp = new SysHandlePermissions();
                        shp.setId(id);
                        shp.setDefaultHandlePermissionId(defaultHandlePermissionId);
                        shp.setAdminUserPermissionAllotId(adminUserPermissionAllotId);
                        shp.setRolePermissionAllotId(rolePermissionAllotId);
                        shp.setMenuId(menuId);
                        shp.setName(name);
                        shp.setPageName(pageName);
                        shp.setCode(code);
                        shp.setTagName(tagName);
                        shp.setInnerHtml(innerHtml);
                        shp.setIdAttr(idAttr);
                        shp.setWeight(weight);
                        shp.setIsForbidden(isForbidden);
                        shp.setCreateUserId(loginUserId);
                        shp.setCreateTime(new Timestamp(System.currentTimeMillis()));
                        shp.setVersion(0);
                        handlePermissionsList.add(shp);
                    }
                }
                List<SysHandlePermissionsClasses> handlePermissionsClassesList = new ArrayList<>();
                if (!isParseError) {
                    //已存在操作权限class属性
                    String sqlForHandleClasses = "SELECT id FROM sys_handle_permissions_classes WHERE handlePermissionId IS NOT NULL";
                    List<Map<String, Object>> handleClassesList = this.databasePreserveService.findForJdbc(sqlForHandleClasses, null);
                    List<String> handleClassesIdList = new ArrayList<>();
                    for (Map<String, Object> map : handleClassesList) {
                        handleClassesIdList.add(map.get("id").toString());
                    }
                    //解析操作权限class属性
                    JSONArray handleClasses = jsonObject.getJSONArray("handleClasses");
                    for (int i = 0, size = handleClasses.size(); i < size; i++) {
                        JSONObject obj = handleClasses.getJSONObject(i);
                        String id = JSONUtil.getStringVal(obj, "id");
                        if (StringUtils.isBlank(id)) {
                            isParseError = true;
                            break;
                        }
                        String handlePermissionId = JSONUtil.getStringVal(obj, "handlePermissionId");
                        if (handleClassesIdList.contains(id) || StringUtils.isBlank(handlePermissionId)) {
                            continue;
                        }
                        String name = JSONUtil.getStringVal(obj, "name");
                        int weight = JSONUtil.getIntVal(obj, "weight");
                        Boolean isForbidden = JSONUtil.getBooleanVal(obj, "isForbidden");
                        SysHandlePermissionsClasses shpc = new SysHandlePermissionsClasses();
                        shpc.setId(id);
                        shpc.setHandlePermissionId(handlePermissionId);
                        shpc.setName(name);
                        shpc.setWeight(weight);
                        shpc.setIsForbidden(isForbidden);
                        shpc.setCreateUserId(loginUserId);
                        shpc.setCreateTime(new Timestamp(System.currentTimeMillis()));
                        shpc.setVersion(0);
                        handlePermissionsClassesList.add(shpc);
                    }
                }
                List<SysHandlePermissionsStyles> handlePermissionsStylesList = new ArrayList<>();
                if (!isParseError) {
                    //已存在操作权限style属性
                    String sqlForHandleStyles = "SELECT id FROM sys_handle_permissions_styles WHERE handlePermissionId IS NOT NULL";
                    List<Map<String, Object>> handleStyleList = this.databasePreserveService.findForJdbc(sqlForHandleStyles, null);
                    List<String> handleStyleIdList = new ArrayList<>();
                    for (Map<String, Object> map : handleStyleList) {
                        handleStyleIdList.add(map.get("id").toString());
                    }
                    //解析操作权限style属性
                    JSONArray handleStyles = jsonObject.getJSONArray("handleStyles");
                    for (int i = 0, size = handleStyles.size(); i < size && !isParseError; i++) {
                        JSONObject obj = handleStyles.getJSONObject(i);
                        String id = JSONUtil.getStringVal(obj, "id");
                        if (StringUtils.isBlank(id)) {
                            isParseError = true;
                            break;
                        }
                        String handlePermissionId = JSONUtil.getStringVal(obj, "handlePermissionId");
                        if (handleStyleIdList.contains(id) || StringUtils.isBlank(handlePermissionId)) {
                            continue;
                        }
                        String name = JSONUtil.getStringVal(obj, "name");
                        int weight = JSONUtil.getIntVal(obj, "weight");
                        Boolean isForbidden = JSONUtil.getBooleanVal(obj, "isForbidden");
                        SysHandlePermissionsStyles shps = new SysHandlePermissionsStyles();
                        shps.setId(id);
                        shps.setHandlePermissionId(handlePermissionId);
                        shps.setName(name);
                        shps.setWeight(weight);
                        shps.setIsForbidden(isForbidden);
                        shps.setCreateUserId(loginUserId);
                        shps.setCreateTime(new Timestamp(System.currentTimeMillis()));
                        shps.setVersion(0);
                        handlePermissionsStylesList.add(shps);
                    }
                }
                List<SysHandlePermissionsEvents> handlePermissionsEventsList = new ArrayList<>();
                if (!isParseError) {
                    //已存在操作权限event属性
                    String sqlForHandleEvents = "SELECT id FROM sys_handle_permissions_events WHERE handlePermissionId IS NOT NULL";
                    List<Map<String, Object>> handleEventsList = this.databasePreserveService.findForJdbc(sqlForHandleEvents, null);
                    List<String> handleEventIdList = new ArrayList<>();
                    for (Map<String, Object> map : handleEventsList) {
                        handleEventIdList.add(map.get("id").toString());
                    }
                    //解析操作权限event属性
                    JSONArray handleEvents = jsonObject.getJSONArray("handleEvents");
                    for (int i = 0, size = handleEvents.size(); i < size && !isParseError; i++) {
                        JSONObject obj = handleEvents.getJSONObject(i);
                        String id = JSONUtil.getStringVal(obj, "id");
                        if (StringUtils.isBlank(id)) {
                            isParseError = true;
                            break;
                        }
                        String handlePermissionId = JSONUtil.getStringVal(obj, "handlePermissionId");
                        if (handleEventIdList.contains(id) || StringUtils.isBlank(handlePermissionId)) {
                            continue;
                        }
                        String name = JSONUtil.getStringVal(obj, "name");
                        String function = JSONUtil.getStringVal(obj, "function");
                        int weight = JSONUtil.getIntVal(obj, "weight");
                        Boolean isForbidden = JSONUtil.getBooleanVal(obj, "isForbidden");
                        SysHandlePermissionsEvents shpe = new SysHandlePermissionsEvents();
                        shpe.setId(id);
                        shpe.setHandlePermissionId(handlePermissionId);
                        shpe.setName(name);
                        shpe.setFunction(function);
                        shpe.setWeight(weight);
                        shpe.setIsForbidden(isForbidden);
                        shpe.setCreateUserId(loginUserId);
                        shpe.setCreateTime(new Timestamp(System.currentTimeMillis()));
                        shpe.setVersion(0);
                        handlePermissionsEventsList.add(shpe);
                    }
                }
                List<SysHandlePermissionsAttrs> handlePermissionsAttrsList = new ArrayList<>();
                if (!isParseError) {
                    //已存在操作权限attr属性
                    String sqlHandleAttrs = "SELECT id FROM sys_handle_permissions_attrs WHERE handlePermissionId IS NOT NULL";
                    List<Map<String, Object>> handleAttrList = this.databasePreserveService.findForJdbc(sqlHandleAttrs, null);
                    List<String> handleAttrIdList = new ArrayList<>();
                    for (Map<String, Object> map : handleAttrList) {
                        handleAttrIdList.add(map.get("id").toString());
                    }
                    //解析操作权限attr属性
                    JSONArray handleAttrs = jsonObject.getJSONArray("handleAttrs");
                    for (int i = 0, size = handleAttrs.size(); i < size && !isParseError; i++) {
                        JSONObject obj = handleAttrs.getJSONObject(i);
                        String id = JSONUtil.getStringVal(obj, "id");
                        if (StringUtils.isBlank(id)) {
                            isParseError = true;
                            break;
                        }
                        String handlePermissionId = JSONUtil.getStringVal(obj, "handlePermissionId");
                        if (handleAttrIdList.contains(id) || StringUtils.isBlank(handlePermissionId)) {
                            continue;
                        }
                        String name = JSONUtil.getStringVal(obj, "name");
                        String value = JSONUtil.getStringVal(obj, "value");
                        int weight = JSONUtil.getIntVal(obj, "weight");
                        Boolean isForbidden = JSONUtil.getBooleanVal(obj, "isForbidden");
                        SysHandlePermissionsAttrs shpa = new SysHandlePermissionsAttrs();
                        shpa.setId(id);
                        shpa.setHandlePermissionId(handlePermissionId);
                        shpa.setName(name);
                        shpa.setValue(value);
                        shpa.setWeight(weight);
                        shpa.setIsForbidden(isForbidden);
                        shpa.setCreateUserId(loginUserId);
                        shpa.setCreateTime(new Timestamp(System.currentTimeMillis()));
                        shpa.setVersion(0);
                        handlePermissionsAttrsList.add(shpa);
                    }
                }
                if (!isParseError) {
                    try {
                        //批量新增菜单
                        Collections.sort(menuPermissionsList, (SysMenuPermissions o1, SysMenuPermissions o2) -> {
                            boolean b = o1.getpId() == null || (o1.getpId() != null && o1.getpId().equals("null"));
                            boolean b1 = o2.getpId() == null || (o2.getpId() != null && o2.getpId().equals("null"));
                            if (b && !b1) {
                                return -1;
                            } else if (b1 && !b) {
                                return 1;
                            } else {
                                return 0;
                            }
                        });
                        for (SysMenuPermissions sysMenuPermissions : menuPermissionsList) {
                            if (sysMenuPermissions.getpId() != null && sysMenuPermissions.getpId().equals("null")) {
                                sysMenuPermissions.setpId(null);
                            }
                        }
                        List<Object> menuPermissionsObjectList = new ArrayList<>();
                        menuPermissionsObjectList.addAll(menuPermissionsList);
                        if (!menuPermissionsObjectList.isEmpty()) {
                            this.databasePreserveService.jdbcBatchSave(menuPermissionsObjectList);
                        }
                        if (!handlePermissionsList.isEmpty()) {
                            //批量新增菜单操作权限
                            List<Object> handlePermissionsObjectList = new ArrayList<>();
                            handlePermissionsObjectList.addAll(handlePermissionsList);
                            this.databasePreserveService.jdbcBatchSave(handlePermissionsObjectList);
                        }
                        if (!handlePermissionsClassesList.isEmpty()) {
                            //批量新增菜单操作权限class属性
                            List<Object> handlePermissionsClassesObjectList = new ArrayList<>();
                            handlePermissionsClassesObjectList.addAll(handlePermissionsClassesList);
                            this.databasePreserveService.jdbcBatchSave(handlePermissionsClassesObjectList);
                        }
                        if (!handlePermissionsStylesList.isEmpty()) {
                            //批量新增菜单操作权限style属性
                            List<Object> handlePermissionsStyleObjectList = new ArrayList<>();
                            handlePermissionsStyleObjectList.addAll(handlePermissionsStylesList);
                            this.databasePreserveService.jdbcBatchSave(handlePermissionsStyleObjectList);
                        }
                        if (!handlePermissionsEventsList.isEmpty()) {
                            //批量新增菜单操作权限event属性
                            List<Object> handlePermissionsEventObjectList = new ArrayList<>();
                            handlePermissionsEventObjectList.addAll(handlePermissionsEventsList);
                            this.databasePreserveService.jdbcBatchSave(handlePermissionsEventObjectList);
                        }
                        if (!handlePermissionsAttrsList.isEmpty()) {
                            //批量新增菜单操作权限event属性
                            List<Object> handlePermissionsAttrObjectList = new ArrayList<>();
                            handlePermissionsAttrObjectList.addAll(handlePermissionsAttrsList);
                            this.databasePreserveService.jdbcBatchSave(handlePermissionsAttrObjectList);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        ajr.setResCode(-1);
                        ajr.setResMsg("导入失败(" + e.getMessage() + ")!");
                    }
                } else {
                    ajr.setResCode(-1);
                    ajr.setResMsg("参数解析错误!");
                }
            } else {
                ajr.setResCode(-1);
                ajr.setResMsg("参数格式错误!");
            }
        }
        return ajr.jsonResponse(false);
    }
}
